package com.sudo.rpc.server.utils;

import org.hyperic.sigar.*;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Properties;

/**
 * author：为道日损 2020-07-03 11:42
 * webSite：https://www.sudo.ren
 */
public class SysInfoUtil {
    public final static boolean IS_LINUX = System.getProperty("os.name").toLowerCase().contains("linux");
    private final static Properties PROPS = System.getProperties();
    private final static Runtime R = Runtime.getRuntime();

    final public static Sigar SIGAR = new Sigar();
    final public static DecimalFormat DF = new DecimalFormat("#.00");

    public static void setServerInfo(Map<String, Object> map) {
        // ==== 服务器信息 ====
        InetAddress address;
        try {
            address = InetAddress.getLocalHost();
            //计算机名
            map.put("server.name", address.getHostName());
            //IP地址
            map.put("server.ip",address.getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        //操作系统名称
        map.put("server.os.name",PROPS.getProperty("os.name"));
        //系统架构
        map.put("server.os.arch",PROPS.getProperty("os.arch"));

    }

    public static void setJavaInfo(Map<String, Object> map) {
        // ==== Java信息 ====
        //java环境
        map.put("java.version", PROPS.getProperty("java.version"));
        //java安装路径
        map.put("java.home", PROPS.getProperty("java.home"));
        //java虚拟机名称
        map.put("java.vm.name", PROPS.getProperty("java.vm.name"));
        long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault());
        String dateTime = localDateTime.format(dtf);
        //java启动时间
        map.put("java.start.time", dateTime);
        //java运行时间
        map.put("java.run.time","0min");
        //java项目路径
        map.put("java.project.path", System.getProperty("user.dir"));
    }

    /**
     * b)CPU的总量（单位：HZ）及CPU的相关信息
     */
    public static void setCpuInfo(Map<String,Object> map) {
        CpuInfo info;
        try {
            info = SIGAR.getCpuInfoList()[0];
            // CPU的总量MHz
            map.put("cpu.mhz",info.getMhz()+"Hz");
            // 获得CPU的卖主，如：Intel
            map.put("cpu.vendor",info.getVendor());
            // 获得CPU的类别，如：Calderon
            map.put("cpu.model",info.getModel());
            // 缓冲存储器数量
            map.put("cpu.cache.size",info.getCacheSize());
            //cpu内核数
            int cores = R.availableProcessors();
            map.put("cpu.core.size",cores);
        } catch (SigarException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * b)Mem的大小及内存的相关信息
     */
    public static void setMemInfo(Map<String,Object> map) {
        Mem mem;
        Swap swap;
        try {
            mem = SIGAR.getMem();
            // 内存大小
            double total = (double) mem.getTotal()/1024/1024/1024;
            map.put("mem.total", DF.format(total) + "G");
            // RAM大小
            double ram = (double) mem.getRam()/1024;
            map.put("mem.ram",DF.format(ram)+"G");

            //JVM内存总量mem.jvm.total
            double jvmTotal = (double) R.totalMemory()/1024/1024;
            map.put("mem.jvm.total", DF.format(jvmTotal)+ "M");

            swap = SIGAR.getSwap();
            // swap大小
            double swapTotal = (double) swap.getTotal()/1024/1024/1024;
            map.put("swap.total",DF.format(swapTotal) + "G");
        } catch (SigarException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 硬盘信息
     * @param map 参数
     */
    public static void setHardDiskInfo(Map<String, Object> map) {
        FileSystem[] fileSystem;
        try {
            fileSystem = SIGAR.getFileSystemList();
            for (int i = 0; i < fileSystem.length; i++) {
                if (IS_LINUX && (!fileSystem[i].getDevName().startsWith("/dev/"))) {
                    continue;
                }
                map.put("filesystem"+i+".name", fileSystem[i].getDevName());
                map.put("filesystem"+i+".type.name", fileSystem[i].getSysTypeName());
                map.put("filesystem" + i + ".type", fileSystem[i].getType());
                map.put("filesystem" + i + ".dir.name", fileSystem[i].getDirName());
                FileSystemUsage usage = SIGAR.getFileSystemUsage(fileSystem[i].getDirName());

                //以G为单位
                double total = (double) usage.getTotal() /1024/1024;
                map.put("filesystem" + i + ".total", DF.format(total));
                double used = (double) usage.getUsed()/1024/1024;
                map.put("filesystem" + i + ".used", DF.format(used));
                double avail = (double) usage.getAvail()/1024/1024;
                map.put("filesystem" + i + ".avail", DF.format(avail));
                double free = (double) usage.getFree()/1024/1024;
                map.put("filesystem" + i + ".free", DF.format(free));
                map.put("filesystem" + i + ".used.percent", usage.getUsePercent());

            }
        } catch (SigarException ex) {
            ex.printStackTrace();
        }
    }


}
